package com.ruoyi.campus.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.campus.domain.SecurityGuard;
import com.ruoyi.campus.domain.PatrolPoint;
import com.ruoyi.campus.domain.Department;
import com.ruoyi.campus.mapper.SecurityGuardMapper;
import com.ruoyi.campus.mapper.PatrolPointMapper;
import com.ruoyi.campus.mapper.DepartmentMapper;
import com.ruoyi.campus.service.ISecurityGuardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 安全员信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-29
 */
@Service
public class SecurityGuardServiceImpl implements ISecurityGuardService
{
    private static final Logger log = LoggerFactory.getLogger(SecurityGuardServiceImpl.class);
    
    @Autowired
    private SecurityGuardMapper securityGuardMapper;
    
    @Autowired
    private PatrolPointMapper patrolPointMapper;
    
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询安全员信息
     * 
     * @param guardId 安全员信息主键
     * @return 安全员信息
     */
    @Override
    public SecurityGuard selectSecurityGuardByGuardId(Long guardId)
    {
        return securityGuardMapper.selectSecurityGuardByGuardId(guardId);
    }

    /**
     * 查询安全员信息列表
     * 
     * @param securityGuard 安全员信息
     * @return 安全员信息
     */
    @Override
    public List<SecurityGuard> selectSecurityGuardList(SecurityGuard securityGuard)
    {
        return securityGuardMapper.selectSecurityGuardList(securityGuard);
    }

    /**
     * 新增安全员信息
     * 
     * @param securityGuard 安全员信息
     * @return 结果
     */
    @Override
    public int insertSecurityGuard(SecurityGuard securityGuard, String operName)
    {
        // 校验姓名+手机号唯一性
        if (StringUtils.isNotEmpty(securityGuard.getName()) && StringUtils.isNotEmpty(securityGuard.getPhoneNumber()))
        {
            SecurityGuard existGuard = securityGuardMapper.checkNameAndPhoneUnique(securityGuard.getName(), securityGuard.getPhoneNumber(), null);
            if (existGuard != null)
            {
                throw new RuntimeException("安全员姓名+手机号已存在，请检查后重新输入");
            }
        }
        
        // 校验部门是否存在
        if (securityGuard.getDeptId() != null)
        {
            Department dept = departmentMapper.selectDepartmentByDeptId(securityGuard.getDeptId());
            if (dept == null)
            {
                throw new RuntimeException("所选部门不存在，请重新选择");
            }
            if ("1".equals(dept.getStatus()))
            {
                throw new RuntimeException("所选部门已停用，请重新选择");
            }
        }
        
        securityGuard.setCreateTime(DateUtils.getNowDate());
        securityGuard.setCreateBy(operName);
        return securityGuardMapper.insertSecurityGuard(securityGuard);
    }

    /**
     * 修改安全员信息
     * 
     * @param securityGuard 安全员信息
     * @return 结果
     */
    @Override
    public int updateSecurityGuard(SecurityGuard securityGuard, String operName)
    {
        // 校验姓名+手机号唯一性
        if (StringUtils.isNotEmpty(securityGuard.getName()) && StringUtils.isNotEmpty(securityGuard.getPhoneNumber()))
        {
            SecurityGuard existGuard = securityGuardMapper.checkNameAndPhoneUnique(securityGuard.getName(), securityGuard.getPhoneNumber(), securityGuard.getGuardId());
            if (existGuard != null)
            {
                throw new RuntimeException("安全员姓名+手机号已存在，请检查后重新输入");
            }
        }
        
        // 校验部门是否存在
        if (securityGuard.getDeptId() != null)
        {
            Department dept = departmentMapper.selectDepartmentByDeptId(securityGuard.getDeptId());
            if (dept == null)
            {
                throw new RuntimeException("所选部门不存在，请重新选择");
            }
            if ("1".equals(dept.getStatus()))
            {
                throw new RuntimeException("所选部门已停用，请重新选择");
            }
        }
        
        securityGuard.setUpdateTime(DateUtils.getNowDate());
        securityGuard.setUpdateBy(operName);
        return securityGuardMapper.updateSecurityGuard(securityGuard);
    }

    /**
     * 批量删除安全员信息
     * 
     * @param guardIds 需要删除的安全员信息主键
     * @return 结果
     */
    @Override
    public int deleteSecurityGuardByGuardIds(String guardIds)
    {
        return securityGuardMapper.deleteSecurityGuardByGuardIds(Convert.toStrArray(guardIds));
    }

    /**
     * 删除安全员信息信息
     * 
     * @param guardId 安全员信息主键
     * @return 结果
     */
    @Override
    public int deleteSecurityGuardByGuardId(Long guardId)
    {
        return securityGuardMapper.deleteSecurityGuardByGuardId(guardId);
    }

    /**
     * 根据安全员ID查询绑定的点位列表
     * 
     * @param guardId 安全员ID
     * @return 绑定的点位列表
     */
    @Override
    public List<PatrolPoint> selectPatrolPointsByGuardId(Long guardId)
    {
        PatrolPoint patrolPoint = new PatrolPoint();
        patrolPoint.setGuardId(guardId);
        return patrolPointMapper.selectPatrolPointList(patrolPoint);
    }

    /**
     * 校验安全员姓名+手机号是否唯一
     *
     * @param name 安全员姓名
     * @param phoneNumber 手机号
     * @param guardId 安全员ID（修改时传入，新增时为null）
     * @return 结果
     */
    @Override
    public boolean checkNameAndPhoneUnique(String name, String phoneNumber, Long guardId)
    {
        SecurityGuard existGuard = securityGuardMapper.checkNameAndPhoneUnique(name, phoneNumber, guardId);
        if (existGuard != null)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 批量导入安全员信息
     *
     * @param securityGuardList 安全员信息列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSecurityGuard(List<SecurityGuard> securityGuardList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(securityGuardList) || securityGuardList.size() == 0)
        {
            throw new RuntimeException("导入安全员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (SecurityGuard securityGuard : securityGuardList)
        {
            try
            {
                // 数据验证
                String validationError = validateSecurityGuardData(securityGuard);
                if (StringUtils.isNotEmpty(validationError))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、安全员 " + securityGuard.getName() + " 导入失败：" + validationError);
                    continue;
                }
                
                // 验证是否存在这个安全员（根据姓名+手机号）
                SecurityGuard existGuard = securityGuardMapper.checkNameAndPhoneUnique(securityGuard.getName(), securityGuard.getPhoneNumber(), null);
                
                if (StringUtils.isNull(existGuard))
                {
                    // 新增安全员
                    securityGuard.setCreateBy(operName);
                    securityGuard.setCreateTime(DateUtils.getNowDate());
                    
                    // 处理部门名称转换为部门ID
                    if (StringUtils.isNotEmpty(securityGuard.getDeptName()))
                    {
                        Long deptId = securityGuardMapper.selectDeptIdByDeptName(securityGuard.getDeptName());
                        if (deptId != null)
                        {
                            securityGuard.setDeptId(deptId);
                        }
                        else
                        {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、安全员 " + securityGuard.getName() + " 导入失败：" + securityGuard.getDeptName() + "部门不存在，请先在部门管理中新增");
                            continue;
                        }
                    }
                    
                    securityGuardMapper.insertSecurityGuard(securityGuard);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、安全员 " + securityGuard.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 更新安全员
                    securityGuard.setGuardId(existGuard.getGuardId());
                    securityGuard.setUpdateBy(operName);
                    securityGuard.setUpdateTime(DateUtils.getNowDate());
                    
                    // 处理部门名称转换为部门ID
                    if (StringUtils.isNotEmpty(securityGuard.getDeptName()))
                    {
                        Long deptId = securityGuardMapper.selectDeptIdByDeptName(securityGuard.getDeptName());
                        if (deptId != null)
                        {
                            securityGuard.setDeptId(deptId);
                        }
                        else
                        {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、安全员 " + securityGuard.getName() + " 更新失败：" + securityGuard.getDeptName() + "部门不存在，请先在部门管理中新增");
                            continue;
                        }
                    }
                    
                    securityGuardMapper.updateSecurityGuard(securityGuard);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、安全员 " + securityGuard.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、安全员 " + securityGuard.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、安全员 " + securityGuard.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 验证安全员数据
     *
     * @param securityGuard 安全员信息
     * @return 验证错误信息
     */
    private String validateSecurityGuardData(SecurityGuard securityGuard)
    {
        if (StringUtils.isEmpty(securityGuard.getName()))
        {
            return "安全员姓名不能为空";
        }
        if (StringUtils.isEmpty(securityGuard.getDeptName()))
        {
            return "所属部门名称不能为空";
        }
        if (StringUtils.isEmpty(securityGuard.getPhoneNumber()))
        {
            return "手机号不能为空";
        }
        return null;
    }
}
